<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { createTableDataApi, deleteTableDataApi, updateTableDataApi, getTableDataApi } from "@/api/table"
import { type CreateOrUpdateTableRequestData, type GetTableData } from "@/api/table/types/table"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Delete, Upload, RefreshRight, Edit } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

defineOptions({
  // 命名当前组件
  name: "ElementPlus"
})

const des = ref('')
const handleNodeClick = (data: any) => {
  des.value = data.des
}

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateTableRequestData = {
  id: undefined,
  username: "",
  password: ""
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateTableRequestData>(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
const formRules: FormRules<CreateOrUpdateTableRequestData> = {
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  password: [{ required: true, trigger: "blur", message: "请输入密码" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = formData.value.id === undefined ? createTableDataApi : updateTableDataApi
    api(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
}
//#endregion

//#region 删
const handleDelete = (row: GetTableData) => {
  ElMessageBox.confirm(`正在删除用户：${row.username}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row: GetTableData) => {
  dialogVisible.value = true
  formData.value = JSON.parse(JSON.stringify(row))
}
//#endregion

//#region 查
const tableData = ref([
  {
    email: "201111",
    email1: "张强",
    email2: "2011-02-03",
    email3: "部门经理",
    email4: "物流部门",
    email5: "13722128888"
  },
  {
    email: "201111",
    email1: "张强1",
    email2: "2011-02-03",
    email3: "供应商",
    email4: "物资部门",
    email5: "13722128888"
  }
])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  username: "",
  phone: ""
})
const getTableData = () => {
  loading.value = true
  getTableDataApi({
    currentPage: paginationData.currentPage,
    size: paginationData.pageSize,
    username: searchData.username || undefined,
    phone: searchData.phone || undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      tableData.value = data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

/** 监听分页参数的变化 */
// watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

interface Tree {
  label: string
  children?: Tree[]
}
const defaultProps = {
  children: "children",
  label: "label"
}
const data = [
  {
    label: "物流起运部",
    des: "起运、物流大部门 包含车联网",
    children: [
      {
        label: "物流中心",
        des: "物流部门 包含计划组，配送组",
        children: [
          {
            label: "张三",
            des: "经理，负责大件运输、审批等。电话：13722128888",
          },
          {
            label: "1班组",
            des: "物流班车 派送",
          },
          {
            label: "2班组"
          },
          {
            label: "3班组"
          }
        ]
      },
      {
        label: "综合室",
        children: [
          {
            label: "综合1"
          },
          {
            label: "综合2"
          },
          {
            label: "综合3"
          }
        ]
      }
    ]
  },
  {
    label: "生产部",
    children: [
      {
        label: "一车间",
        children: [
          {
            label: "1班组"
          },
          {
            label: "2班组"
          },
          {
            label: "2班组"
          }
        ]
      }
    ]
  },
  {
    label: "仓库",
    children: [
      {
        label: "一车间",
        children: [
          {
            label: "1班组"
          },
          {
            label: "2班组"
          },
          {
            label: "2班组"
          }
        ]
      }
    ]
  },
  {
    label: "金工部",
    children: [
      {
        label: "一车间",
        children: [
          {
            label: "1班组"
          },
          {
            label: "2班组"
          },
          {
            label: "2班组"
          }
        ]
      }
    ]
  },
  {
    label: "涂装部",
    children: [
      {
        label: "一车间",
        children: [
          {
            label: "1班组"
          },
          {
            label: "2班组"
          },
          {
            label: "2班组"
          }
        ]
      }
    ]
  }
]
</script>

<template>
  <div class="app-container flex">
    <div class="bg-white mr-2 w-1/6">
      <div class="p-2 text-base"><span class="pr-10">部门列表</span> <el-button :icon="Search" circle /></div>
      <el-tree class="min-w-30" :data="data" :props="defaultProps" @node-click="handleNodeClick" />
    </div>
    <div class="w-5/6">
      <el-card shadow="never" class="mb-5">
        角色介绍：{{ des }}
      </el-card>
      <el-card v-loading="loading" shadow="never" class="search-wrapper">
        <el-form ref="searchFormRef" :inline="true" :model="searchData" label-width="80px">
          <el-form-item prop="username" label="用户名">
            <el-input v-model="searchData.username" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="phone" label="姓名">
            <el-input v-model="searchData.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="phone" label="创建时间">
            <el-input v-model="searchData.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="phone" label="角色">
            <el-input v-model="searchData.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="phone" label="所属部门">
            <el-input v-model="searchData.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="phone" label="电话">
            <el-input v-model="searchData.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card v-loading="loading" shadow="never">
        <div class="toolbar-wrapper">
          <div>
            <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增用户</el-button>
            <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
            <el-button>导出</el-button>
            <el-button type="success">导入</el-button>
          </div>
          <div>
            <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
            <el-tooltip content="刷新当前页">
              <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
            </el-tooltip>
          </div>
        </div>
        <div class="table-wrapper">
          <el-table :data="tableData">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="email" label="用户名" align="center" />
            <el-table-column prop="email1" label="姓名" align="center" />
            <el-table-column prop="email2" label="创建时间" align="center" />
            <el-table-column prop="email3" label="角色" align="center" />
            <el-table-column prop="email4" label="部门" align="center" />
            <el-table-column prop="email4" label="车间" align="center" />
            <el-table-column prop="email4" label="班组" align="center" />
            <el-table-column prop="email5" label="电话" align="center" />
            <el-table-column fixed="right" label="操作" width="150" align="center">
              <template #default="scope">
                <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
                <el-button type="warning" text bg size="small" @click="handleUpdate(scope.row)">禁用</el-button>
                <div>
                  <el-button type="warning" text bg size="small" @click="handleDelete(scope.row)">解冻</el-button>
                  <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pager-wrapper">
          <el-pagination
            background
            :layout="paginationData.layout"
            :page-sizes="paginationData.pageSizes"
            :total="paginationData.total"
            :page-size="paginationData.pageSize"
            :currentPage="paginationData.currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      <!-- 新增/修改 -->
      <el-dialog
        v-model="dialogVisible"
        :title="formData.id === undefined ? '新增用户' : '修改用户'"
        @closed="resetForm"
        width="30%"
      >
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
          <el-form-item prop="username" label="用户名/工号">
            <el-input v-model="formData.username" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="username" label="姓名">
            <el-input v-model="formData.username" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="username" label="电话">
            <el-input v-model="formData.username" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="username" label="部门">
            <el-select v-model="searchData.username" placeholder="请选择" />
          </el-form-item>
          <el-form-item label="车间">
            <el-select v-model="searchData.username" placeholder="请选择" />
          </el-form-item>
          <el-form-item label="班组">
            <el-select v-model="searchData.username" placeholder="请选择" />
          </el-form-item>
          <el-form-item prop="username" label="备注">
            <el-input v-model="formData.username" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
